
(function(){
	
	//简化一下document.queryselector
	var $ = function(className){
		var ele = document.querySelectorAll(className);
		if(ele.length > 1){
			return  document.querySelectorAll(className);
		}
		else{
			return  document.querySelector(className);
		}
	}
	
	//添加trim()方法
	String.prototype.trim=function(){
　　    return this.replace(/(^\s*)|(\s*$)/g, "");
　　 }
	
	var Chat = function(){
		this.socket = null;
	}
	
	Chat.prototype = {
		
		init: function(){
			
			var that = this;
			this.socket = io.connect();
			
			this.socket.on("connect",function(){
				
				$(".submitnick").addEventListener("click",function(){

					var nickname = $(".nick").value.trim();
					
					if(nickname.length >= 1){
						that.socket.emit("login",nickname);
					}
					else{
						alert("请输入一个正确的昵称");
					}	
				});
			});
			
			this.socket.on("nickExists",function(){
				alert("您的昵称已存在");
			});
			
			this.socket.on("loginSuccess",function(users){
				
				$(".content").style.display = "block";
				$(".nickbox").style.display = "none";
				
				$(".users-list").innerHTML = "";
				for(var i = 0;i < users.length;i++){
					var ptag = document.createElement("p");
					$(".users-list").appendChild(ptag);
					ptag.innerHTML = users[i];
				}
				
				//开始聊天
				$(".submitinf").addEventListener("click",function(){
					var sendmsg = $(".nick").value.trim() + "：" + $(".message").value.trim();
					if(sendmsg.length > 0){
						that.socket.emit("sendMsg",sendmsg,$(".nick").value.trim());
					}
					else{
						alert("您发送的消息为空");
					}
				});
				
			});
			
			this.socket.on("system",function(username,count,type){
				var message = "系统通知：" + username + (type == "login" ? "加入了" : "退出了") + "聊天室";
				
				$(".onlines").innerHTML = count;
				
				//用户登入或退出通知
				var ptagSystem = document.createElement("p");
				ptagSystem.className = "systemInf";
				ptagSystem.innerHTML = message;
				$(".dialog").appendChild(ptagSystem);
			});
			
			this.socket.on("sendSuccess",function(msg,username){
				
				var ptagUser = document.createElement("p");
				ptagUser.className = "userInf";
				ptagUser.innerHTML = msg;
				$(".dialog").appendChild(ptagUser);
				
				//判断是否为当前用户所发信息
				if(username == $(".nick").value.trim()){
					ptagUser.className = "userInf2";
				}
			});
		},
		
		sendMessage: function(user,msg){
			
		}
	};
	
	//实例化
	var chat = new Chat();
	chat.init();
	
})();

